package com.hengtiansoft.lfy.activity;

import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.chart.DemoHXSDKHelper;
import com.hengtiansoft.lfy.chart.activity.ChatActivity;
import com.hengtiansoft.lfy.chart.fragment.ChatAllHistoryFragment;
import com.hengtiansoft.lfy.chart.applib.controller.HXSDKHelper;
import com.hengtiansoft.lfy.chart.db.InviteMessgeDao;
import com.hengtiansoft.lfy.chart.db.UserDao;
import com.hengtiansoft.lfy.chart.domain.FriendsUser;
import com.hengtiansoft.lfy.chart.domain.InviteMessage;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.db.EvaluatorDBManager;
import com.hengtiansoft.lfy.entity.ServiceResult;
import com.hengtiansoft.lfy.entity.UpdateEntity;
import com.hengtiansoft.lfy.fragment.DialogueFragment;
import com.hengtiansoft.lfy.fragment.ExerciseFragment;
import com.hengtiansoft.lfy.fragment.MyFragment;
import com.hengtiansoft.lfy.fragment.TranslationFragment;
import com.hengtiansoft.lfy.utils.Kdxf_TTSPlayer;
import com.hengtiansoft.lfy.utils.NotificationClickReceiver;
import com.hengtiansoft.lfy.net.NetHelper;
import com.hengtiansoft.lfy.net.NetUtils;
import com.hengtiansoft.lfy.utils.FileUtil;
import com.hengtiansoft.lfy.utils.ScreenUtils;
import com.hengtiansoft.lfy.widget.MyToast;
import com.hyphenate.EMContactListener;
import com.hyphenate.EMGroupChangeListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.HanziToPinyin;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class MainActivity extends BaseActivity {

    protected static final String TAG = "MainActivity";
    private Button[] mTabs;
    private TranslationFragment translationFragment;
    private DialogueFragment dialogueFragment;
    //private ExerciseFragment exerciseFragment;
    private ChatAllHistoryFragment chatAllHistoryFragment;
    private MyFragment myFragment;
    private Fragment[] fragments;
    private int index;
    // 当前fragment的index
    private int currentTabIndex;
    NotificationCompat.Builder mBuilder;
    public NotificationManager mNotificationManager;
    private android.app.AlertDialog.Builder conflictBuilder;
    private android.app.AlertDialog.Builder accountRemovedBuilder;
    private boolean isConflictDialogShow;
    private boolean isAccountRemovedDialogShow;
    private InviteMessgeDao inviteMessgeDao;
    private MyGroupChangeListener groupChangeListener = null;
    // 账号被移除
    private boolean isCurrentAccountRemoved = false;
    private UserDao userDao;
    // 账号在别处登录
    public boolean isConflict = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null && savedInstanceState
                .getBoolean(Constants.ACCOUNT_REMOVED, false)) { //账号是否被删除
            // 防止被移除后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
            // 三个fragment里加的判断同理
            DemoHXSDKHelper.getInstance().logout(true, null);//推出聊天登陆
            finish();
            startActivity(new Intent(this, LoginActivityV2.class)); //重新开启登陆
            return;
        } else if (savedInstanceState != null
                && savedInstanceState.getBoolean("isConflict", false)) { //是否被T
            // 防止被T后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
            // 三个fragment里加的判断同理
            finish();
            startActivity(new Intent(this, LoginActivityV2.class)); //?估计聊天
            return;
        }
        setContentView(R.layout.activity_main);
        EMClient.getInstance().contactManager()
                .setContactListener(new MyContactListener()); //联系人监听
        groupChangeListener = new MyGroupChangeListener();
        // 注册群聊相关的listener
        EMClient.getInstance().groupManager()
                .addGroupChangeListener(groupChangeListener);
        initView();
        //通知
        mNotificationManager = (NotificationManager) getSystemService(
                NOTIFICATION_SERVICE);
        //聊天消息表
        inviteMessgeDao = new InviteMessgeDao(this);
        //联系人表
        userDao = new UserDao(this);

        if (getIntent().getBooleanExtra("conflict", false)
                && !isConflictDialogShow) { //isConflictDialogShow是否显示过弹窗
            //账号在其他地方登陆
            showConflictDialog();
        } else if (getIntent().getBooleanExtra(Constants.ACCOUNT_REMOVED, false)
                && !isAccountRemovedDialogShow) {
            //此账户被移除
            showAccountRemovedDialog();
        }
        translationFragment = new TranslationFragment();
        dialogueFragment = new DialogueFragment();
        //exerciseFragment = new ExerciseFragment();
        chatAllHistoryFragment=new ChatAllHistoryFragment();
        myFragment = new MyFragment();
        fragments = new Fragment[] { translationFragment, dialogueFragment, chatAllHistoryFragment, myFragment };
        // 添加显示第一个fragment
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, translationFragment)
                .add(R.id.fragment_container, dialogueFragment).hide(dialogueFragment).show(translationFragment)
                .commit();

        translationFragment.setDialogClickListener(new TranslationFragment.IDialogListener() {
            @Override
            public void onDialogBtnClick() {
                index = 1;
                if (currentTabIndex != index) {
                    FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
                    trx.setCustomAnimations(R.anim.slide_in_right,R.anim.slide_out_left);
                    trx.hide(fragments[currentTabIndex]);
                    if (!fragments[index].isAdded()) {
                        trx.add(R.id.fragment_container, fragments[index]);
                    }
                    trx.show(fragments[index]).commit();
                }
                mTabs[currentTabIndex].setSelected(false);
                // 把当前tab设为选中状态
                mTabs[index].setSelected(true);
                currentTabIndex = index;
            }
        });
        //禁止右滑关闭
        setSwipeBackEnabled(false);
        //试卷推送
        if(Constants.EVALUATOR_MESSAGE.equals(getIntent().getStringExtra(Constants.EVALUATOR_MESSAGE))) {
            if (mTabs != null) {
                EvaluatorDBManager.getInstance().updateModeState();
                mTabs[2].performClick();
            }
        }
        if(Constants.CHART_MESSAGE.equals(getIntent().getStringExtra(Constants.CHART_MESSAGE))){
            if (mTabs != null) {
                mTabs[2].performClick();
            }
        }
    }
    /**
     * 显示帐号在别处登录dialog
     */
    private void showConflictDialog() {
        isConflictDialogShow = true;
        DemoHXSDKHelper.getInstance().logout(false, null);
        String st = getResources().getString(R.string.Logoff_notification);
        if (!MainActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (conflictBuilder == null)
                    conflictBuilder = new android.app.AlertDialog.Builder(
                            MainActivity.this);
                conflictBuilder.setTitle(st);
                conflictBuilder.setMessage(R.string.connect_conflict);
                conflictBuilder.setPositiveButton(R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                                conflictBuilder = null;
                                finish();
                                startActivity(new Intent(MainActivity.this,
                                       LoginActivityV2.class).putExtra("from","loginout"));
                            }
                        });
                conflictBuilder.setCancelable(false);
                conflictBuilder.create().show();
                isConflict = true;
            } catch (Exception e) {
                EMLog.e(TAG, "---------color conflictBuilder error"
                        + e.getMessage());
            }

        }

    }

    /***
     * 好友变化listener
     *
     */
    public class MyContactListener implements EMContactListener {

        @Override
        public void onContactAdded(String username) {
            // 保存增加的联系人
            Map<String, FriendsUser> localUsers = ((DemoHXSDKHelper) HXSDKHelper
                    .getInstance()).getContactList();
            Map<String, FriendsUser> toAddUsers = new HashMap<String, FriendsUser>();
//            for (String username : usernameList) {
            //string转USER
            FriendsUser user = setUserHead(username);
            // 添加好友时可能会回调added方法两次 判断内存中是否有新的好友
            if (!localUsers.containsKey(username)) { //没有该用户
                //添加用户到数据库
                userDao.saveContact(user);
            }
            toAddUsers.put(username, user);//估计为了再获取昵称
            //    }
            localUsers.putAll(toAddUsers);
            // 刷新ui
            // if (currentTabIndex == 1)
            // refresh();

        }

        @Override
        public void onContactDeleted(final String username) {
            // 被删除
            Map<String, FriendsUser> localUsers = ((DemoHXSDKHelper) HXSDKHelper
                    .getInstance()).getContactList();
            //   for (String username : usernameList) {
            localUsers.remove(username); //内存删除
            userDao.deleteContact(username);//数据库删除
            inviteMessgeDao.deleteMessage(username);//新的好友表删除
            //   }
            runOnUiThread(new Runnable() {
                public void run() {
                    // 如果正在与此用户的聊天页面
                    String st10 = getResources()
                            .getString(R.string.have_you_removed);
                    //如果此用户被删除提示，然后关闭ChartActivity
                    if (ChatActivity.activityInstance != null && username
                            .contains(ChatActivity.activityInstance
                                    .getToChatUsername())) {
                        Toast.makeText(MainActivity.this,
                                ChatActivity.activityInstance
                                        .getToChatUsername() + st10,
                                Toast.LENGTH_SHORT).show();
                        ChatActivity.activityInstance.finish();
                    }
                    // updateUnreadLabel();
                    // 刷新ui
                    // refresh();
                    // chatHistoryFragment.refresh();
                }
            });

        }

        @Override
        public void onContactInvited(String username, String reason) { //收到好友邀请

            // 接到邀请的消息，如果不处理(同意或拒绝)，掉线后，服务器会自动再发过来，所以客户端不需要重复提醒
            List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();

            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getGroupId() == null
                        && inviteMessage.getFrom().equals(username)) { //如果不是群组并且是这个用户名则删除
                    inviteMessgeDao.deleteMessage(username);
                }
            }
            // 自己封装的javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            msg.setReason(reason);//??reason
            Log.d(TAG, username + "请求加你为好友,reason: " + reason);
            // 设置相应status
            msg.setStatus(InviteMessage.InviteMesageStatus.BEINVITEED);//状态 被邀请 0
            notifyNewIviteMessage(msg, 0);//通知和保存 以及消息数量+1

        }

        @Override
        public void onFriendRequestAccepted(String username) { //同意添加好友
            List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();
            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getFrom().equals(username)) { //如果已经有则return
                    return;
                }
            }
            // 自己封装的javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            Log.d(TAG, username + "同意了你的好友请求");
            msg.setStatus(InviteMessage.InviteMesageStatus.BEAGREED); //2 对方已同意
            notifyNewIviteMessage(msg, 1);//同意了你的好友请求

        }

        @Override
        public void onFriendRequestDeclined(String username) {

            // 参考同意，被邀请实现此功能,demo未实现
            Log.d(username, username + "拒绝了你的好友请求");
        }

    }
    /**
     * set head
     *  头像呢？？
     * @param username
     * @return
     */
    FriendsUser setUserHead(String username) {
        FriendsUser user = new FriendsUser(username);
        // user.setUsername(username);
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) { //获取用户昵称环信方法
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        //设置a-z
        if (username.equals(Constants.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(
                    HanziToPinyin.getInstance().get(headerName.substring(0, 1))
                            .get(0).target.substring(0, 1).toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }
        return user;
    }
    /**
     * 保存提示新消息
     *
     * @param msg
     */
    private void notifyNewIviteMessage(InviteMessage msg, int id) {
        saveInviteMsg(msg);
        // 提示有新消息
        HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(null); //震动和声音
        showIntentActivityNotify(msg.getFrom(), id);
    }
    /** 显示通知栏点击跳转到指定Activity */
    public void showIntentActivityNotify(String message, int from) {
        mBuilder = new NotificationCompat.Builder(this);
        String mes = getString(R.string.new_message);
        // //在通知栏上点击此通知后自动清除此通知
        if (from == 0) {
            mes = getString(R.string.request_add_friend);
        } else if (from == 1) {
            mes = getString(R.string.agree_request_add_friend);
        } else if (from == 2) {
            mes = getString(R.string.request_group_chat);
        }
        mBuilder.setAutoCancel(true)
                // 点击后让通知将消失
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText(message + mes).setTicker(message + mes)
                .setSmallIcon(R.drawable.lfy);
        // 点击的意图ACTION是跳转到Intent
        Intent resultIntent = new Intent(this, NotificationClickReceiver.class);
        resultIntent.putExtra(Constants.NEW_FRIEND_MESSAGE,Constants.NEW_FRIEND_MESSAGE);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0,
                resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pendingIntent);
        mNotificationManager.notify(101, mBuilder.build());
    }



    /**
     * 保存邀请等msg
     *
     * @param msg
     */
    private void saveInviteMsg(InviteMessage msg) {
        // 保存msg
        inviteMessgeDao.saveMessage(msg);
        // 未读数加1
        FriendsUser user = ((DemoHXSDKHelper) HXSDKHelper.getInstance())
                .getContactList().get(Constants.NEW_FRIENDS_USERNAME);
        if (user.getUnreadMsgCount() == 0)
            user.setUnreadMsgCount(user.getUnreadMsgCount() + 1);
    }
    // 刷新ui
    public void refresh() {
        // try {
        // // 可能会在子线程中调到这方法
        // runOnUiThread(new Runnable() {
        // public void run() {
        // ContactlistActivity contactlistActivity = new ContactlistActivity();
        // contactlistActivity.refresh();
        // }
        // });
        // } catch (Exception e) {
        // e.printStackTrace();
        // }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        /*if(Constants.EVALUATOR_MESSAGE.equals(intent.getStringExtra(Constants.EVALUATOR_MESSAGE))) {
            if (mTabs != null) {
                EvaluatorDBManager.getInstance().updateModeState();
                mTabs[2].performClick();
            }
        }*/
        if(Constants.CHART_MESSAGE.equals(intent.getStringExtra(Constants.CHART_MESSAGE))){
            if (mTabs != null) {
                mTabs[2].performClick();
            }
        }else {
            if (intent.getBooleanExtra("conflict", false)
                    && !isConflictDialogShow) { //isConflictDialogShow是否显示过弹窗
                //账号在其他地方登陆
                showConflictDialog();
            } else if (intent.getBooleanExtra(Constants.ACCOUNT_REMOVED, false)
                    && !isAccountRemovedDialogShow) {
                //此账户被移除
                showAccountRemovedDialog();
            }
        }
    }

    /**
     * 帐号被移除的dialog
     */
    private void showAccountRemovedDialog() {
        isAccountRemovedDialogShow = true;
        DemoHXSDKHelper.getInstance().logout(true, null);
        String st5 = getResources().getString(R.string.Remove_the_notification);
        if (!MainActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (accountRemovedBuilder == null)
                    accountRemovedBuilder = new android.app.AlertDialog.Builder(
                            MainActivity.this);
                accountRemovedBuilder.setTitle(st5);
                accountRemovedBuilder.setMessage(R.string.em_user_remove);
                accountRemovedBuilder.setPositiveButton(R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                                accountRemovedBuilder = null;
                                finish();
                                startActivity(new Intent(MainActivity.this,
                                        LoginActivityV2.class).putExtra("from","loginout"));
                            }
                        });
                accountRemovedBuilder.setCancelable(false);
                accountRemovedBuilder.create().show();
                isCurrentAccountRemoved = true;
            } catch (Exception e) {
                EMLog.e(TAG, "---------color userRemovedBuilder error"
                        + e.getMessage());
            }
        }
    }

    private void initView() {
        update();
        mTabs = new Button[4];
        mTabs[0] = (Button) findViewById(R.id.btn_translation);
        mTabs[1] = (Button) findViewById(R.id.btn_dialogue);
        mTabs[2] = (Button) findViewById(R.id.btn_chart);
        mTabs[3] = (Button) findViewById(R.id.btn_my);
        // 把第一个tab设为选中状态
        mTabs[0].setSelected(true);
    }
    private String mAppDownloadUrl = null;
    private void update() {
        String version="v" + ScreenUtils.getVersion(self);
         NetHelper.updateApi(self, version, new NetUtils.NetCallBack<ServiceResult>() {
                     @Override
                     public void success(ServiceResult rspData) {
                         UpdateEntity info = (UpdateEntity) rspData;
                         int code = info.getRetcode();
                         String message = info.getMessage();
                         if (code == 0) {
                             String data = info.getData();
                             mAppDownloadUrl = data;
                             // 弹出对话框通知用户更新程序
                             runOnUiThread(new Runnable() {
                                 public void run() {
                                     showUpdataDialog();
                                 }
                             });
                         }

                     }
                     @Override
                     public void failed(String msg) {
                         MyToast.show(self, msg);

                     }
                 }, UpdateEntity.class);
    }
    // 弹出对话框通知用户更新程序
    private void showUpdataDialog() {

            AlertDialog.Builder builer = new AlertDialog.Builder(this);
            builer.setTitle(getString(R.string.version_update_title));
            builer.setMessage(getString(R.string.version_update_message));
            // 当点确定按钮时从服务器上下载 新的apk 然后安装
            builer.setPositiveButton(getString(R.string.confirm),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            Log.i(TAG, "<showUpdataDialog> -- 下载apk");
                            downLoadApk();
                        }
                    });
            // 当点取消按钮时进行登录
            builer.setNegativeButton(getString(R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // 若服务器上的主版本号或次版本号大于当前的主版本号或次版本号，则按取消时，直接退出应用
                            // finish();
                             dialog.dismiss();
                        }
                    });
            AlertDialog dialog = builer.create();
            dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
            dialog.show();
    }
    // 从服务器中下载APK
    protected void downLoadApk() {
        final ProgressDialog pd; // 进度条对话框
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage(getString(R.string.version_updating));
        pd.setCanceledOnTouchOutside(false);
        pd.show();

        new Thread() {
            @Override
            public void run() {
                try {
                    File file = FileUtil.getFileFromServer(self,
                            mAppDownloadUrl, pd, Constants.APK_NAME);
                    sleep(3000);
                    installApk(file);
                    pd.dismiss(); // 结束掉进度条对话框
                } catch (Exception e) {
                    pd.dismiss();
                    e.printStackTrace();
                }
            }
        }.start();
    }
    // 安装apk
    protected void installApk(File file) {
        if (file == null) {
            // showToast(mContext, getString(R.string.version_update_error),
            // Toast.LENGTH_SHORT);
            return;
        }
        Intent intent = new Intent();
        // 执行动作
        intent.setAction(Intent.ACTION_VIEW);
        // 执行的数据类型
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }

    @Override
    public void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);
        if (translationFragment == null && fragment instanceof TranslationFragment) {
            translationFragment = (TranslationFragment)fragment;
        }else if (dialogueFragment == null && fragment instanceof DialogueFragment) {
            dialogueFragment = (DialogueFragment)fragment;
        }else if (chatAllHistoryFragment == null && fragment instanceof ExerciseFragment) {
            chatAllHistoryFragment = (ChatAllHistoryFragment) fragment;
        }else if (myFragment == null && fragment instanceof MyFragment) {
            myFragment = (MyFragment)fragment;
        }
    }
    //修复系统回收导致的frament重影问题
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //super.onSaveInstanceState(outState);
    }
    /**
     * button点击事件
     *
     * @param view
     */
    public void onTabClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_translation:
                index = 0;
                setStatusBar(R.color.white);
                break;
            case R.id.btn_dialogue:
                index = 1;
                setStatusBar(R.color.white);
                break;
            case R.id.btn_chart:
                index = 2;
                setStatusBar(R.color.white);
                break;
            case R.id.btn_my:
                index = 3;
                break;
        }
        if (currentTabIndex != index) {
            Kdxf_TTSPlayer.getInstense().stop();
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            if (index > currentTabIndex)
                trx.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left);
            else
                trx.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
            trx.hide(fragments[currentTabIndex]);
            if (!fragments[index].isAdded()) {
                trx.add(R.id.fragment_container, fragments[index]);
            }
            trx.show(fragments[index]).commit();
        }
        if( index == 0 ){
            translationFragment.setOnFirstVisible();
        }
        mTabs[currentTabIndex].setSelected(false);
        // 把当前tab设为选中状态
        mTabs[index].setSelected(true);
        currentTabIndex = index;
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                MyToast.show(this, "再按一次返回键退出应用");
                exitTime = System.currentTimeMillis();
            } else {
                activityManager.popAllActivity();
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * MyGroupChangeListener
     */
    public class MyGroupChangeListener implements EMGroupChangeListener {
        //收到加入群聊的邀请
        @Override
        public void onInvitationReceived(String groupId, String groupName,
                                         String inviter, String reason) {

            boolean hasGroup = false;
            for (EMGroup group :EMClient.getInstance().groupManager().getAllGroups()) { //获取所有群组环信方法
                if (group.getGroupId().equals(groupId)) { //如果有此群则退出
                    hasGroup = true;
                    break;
                }
            }
            if (!hasGroup)
                return;

            // 被邀请
            String st3 = getResources()
                    .getString(R.string.Invite_you_to_join_a_group_chat);
            EMMessage msg = EMMessage
                    .createReceiveMessage(EMMessage.Type.TXT);
            msg.setChatType(EMMessage.ChatType.GroupChat);
            msg.setFrom(inviter); //邀请人用户名
            msg.setTo(groupId);   //群聊ID
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new EMTextMessageBody(inviter + " " + st3)); //XXX邀请你加入了群聊
            msg.setAttribute("translate",
                    inviter + " invite you to join group chat!"); //英文
            Log.i(TAG, inviter);
            // 保存邀请消息
            EMClient.getInstance().chatManager().saveMessage(msg);
            // 提醒新消息
            HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(msg); //震动和声音
            showIntentGroupActivityNotify(inviter);//邀请你加入群聊通知

        }

        @Override
        public void onInvitationAccepted(String groupId, String inviter,
                                        String reason) {
            //群聊邀请被接受
        }

        @Override
        public void onInvitationDeclined(String groupId, String invitee,
                                         String reason) {
            //群聊邀请被拒绝
        }

        @Override
        public void onUserRemoved(String groupId, String groupName) {
            //当前用户被管理员移除出群聊
            Log.i("supeng","onUserRemoved");
        }

        @Override
        public void onGroupDestroyed(String groupId, String groupName) {
            //群聊被创建者解散
            // 提示用户群被解散
        }

        @Override
        public void onAutoAcceptInvitationFromGroup(String groupId, String inviter, String inviteMessage) {
            boolean hasGroup = false;
            for (EMGroup group :EMClient.getInstance().groupManager().getAllGroups()) { //获取所有群组环信方法
                if (group.getGroupId().equals(groupId)) { //如果有此群则退出
                    hasGroup = true;
                    break;
                }
            }
            if (!hasGroup)
                return;

            // 被邀请
            String st3 = getResources()
                    .getString(R.string.Invite_you_to_join_a_group_chat);
            EMMessage msg = EMMessage
                    .createReceiveMessage(EMMessage.Type.TXT);
            msg.setChatType(EMMessage.ChatType.GroupChat);
            msg.setFrom(inviter); //邀请人用户名
            msg.setTo(groupId);   //群聊ID
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new EMTextMessageBody(inviter + " " + st3)); //XXX邀请你加入了群聊
            msg.setAttribute("translate",
                    inviter + " invite you to join group chat!"); //英文
            Log.i(TAG, inviter);
            // 保存邀请消息
            EMClient.getInstance().chatManager().saveMessage(msg);
            // 提醒新消息
            HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(msg); //震动和声音
            showIntentGroupActivityNotify(inviter);//邀请你加入群聊通知
        }

        // 用户申请加入群聊，收到加群申请
        @Override
        public void onRequestToJoinReceived(String groupId, String groupName,
                                          String applyer, String reason) {

            // 用户申请加入群聊
            InviteMessage msg = new InviteMessage();
            msg.setFrom(applyer);
            msg.setTime(System.currentTimeMillis());
            msg.setGroupId(groupId);
            msg.setGroupName(groupName);
            msg.setReason(reason);
            Log.d(TAG, applyer + " 申请加入群聊：" + groupName);
            msg.setStatus(InviteMessage.InviteMesageStatus.BEAPPLYED);
            notifyNewIviteMessage(msg, 2);
        }
        // 加群申请被同意
        @Override
        public void onRequestToJoinAccepted(String groupId, String groupName,
                                        String accepter) {

            String st4 = getResources()
                    .getString(R.string.Agreed_to_your_group_chat_application);
            // 加群申请被同意
            EMMessage msg = EMMessage
                    .createReceiveMessage(EMMessage.Type.TXT);
            msg.setChatType(EMMessage.ChatType.GroupChat);
            msg.setFrom(accepter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new EMTextMessageBody(accepter + " " + st4));
            // 保存同意消息
            EMClient.getInstance().chatManager().saveMessage(msg);
            // 提醒新消息
            HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(msg);

        }

        @Override
        public void onRequestToJoinDeclined(String groupId, String groupName,
                                          String decliner, String reason) {
            // 加群申请被拒绝，demo未实现
        }
    }

    /** 显示通知栏点击跳转到指定Activity */
    public void showIntentGroupActivityNotify(String message) {
        mBuilder = new NotificationCompat.Builder(this);
        String mes = getString(R.string.invite_group_chart);
        mBuilder.setAutoCancel(true)
                // 点击后让通知将消失
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText(message + mes).setTicker(message + mes)
                .setSmallIcon(R.drawable.lfy);
        // 点击的意图ACTION是跳转到Intent
        Intent resultIntent = new Intent(this,NotificationClickReceiver.class); // MainActivity.class
        resultIntent.putExtra(Constants.CHART_MESSAGE, Constants.CHART_MESSAGE);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0,
                resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pendingIntent);
        mNotificationManager.notify(101, mBuilder.build());
    }

    @Override
    protected void onResume() {
        super.onResume();
//                DemoHXSDKHelper sdkHelper = (DemoHXSDKHelper) DemoHXSDKHelper
//                .getInstance();
        //sdkHelper.pushActivity(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
//                DemoHXSDKHelper sdkHelper = (DemoHXSDKHelper) DemoHXSDKHelper
//               .getInstance();

        // 把此activity 从foreground activity 列表里移除
      //  sdkHelper.popActivity(this);
    }


}
